import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { createJwtToken } from '@/lib/auth/jwt';

// 模拟用户数据
const MOCK_USER = {
  id: '1',
  email: 'admin@example.com',
  name: '管理员',
  role: 'admin',
  password: '123456', // 生产环境中应该使用哈希密码
};

const loginSchema = z.object({
  email: z.string().email(),
  password: z.string(),
  remember: z.boolean().optional(),
});

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const validatedData = loginSchema.parse(body);

    // 在实际应用中，您应该查询数据库进行用户验证
    // 这里我们使用模拟数据来演示
    if (validatedData.email !== MOCK_USER.email || validatedData.password !== MOCK_USER.password) {
      return NextResponse.json(
        { success: false, message: '邮箱或密码不正确' },
        { status: 401 }
      );
    }

    // 创建 JWT token
    const token = await createJwtToken({
      sub: MOCK_USER.id,
      email: MOCK_USER.email,
      name: MOCK_USER.name,
      role: MOCK_USER.role,
    });

    // 返回用户信息和 token
    return NextResponse.json({
      success: true,
      message: '登录成功',
      status: 200,
      data: {
        user: {
          id: MOCK_USER.id,
          email: MOCK_USER.email,
          name: MOCK_USER.name,
          role: MOCK_USER.role,
        },
        token,
      }
    });
  } catch (error) {
    console.error('登录错误', error);
    
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { success: false, message: '无效的请求数据', errors: error.flatten().fieldErrors },
        { status: 400 }
      );
    }
    
    return NextResponse.json(
      { success: false, message: '登录失败，请稍后再试' },
      { status: 500 }
    );
  }
} 